<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2>登录系统</h2>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="账号" prop="idNumber">
          <el-input 
            v-model.trim="loginForm.idNumber" 
            placeholder="请输入学号/工号"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input
            v-model.trim="loginForm.password"
            type="password"
            show-password
            placeholder="请输入密码"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleLogin">
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
          <el-link
            type="primary"
            class="register-link"
            @click="$router.push('/register')"
          >
            注册账号
          </el-link>
        </el-form-item>

        <!-- 测试账号提示 -->
        <!-- <div class="test-accounts">
          <p>测试账号：</p>
          <ul>
            <li>管理员：admin / 123456</li>
            <li>教师：teacher / 123456</li>
            <li>学生：student / 123456</li>
          </ul>
        </div> -->
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import { login } from '@/api/auth'

const router = useRouter()
const authStore = useAuthStore()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = ref({
  idNumber: '',
  password: ''
})

const rules = {
  idNumber: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9]{6,20}$/, 
      message: '账号必须为6-20个字母或数字', 
      trigger: 'blur' 
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
     { 
      min: 6, 
      max: 20, 
      message: '密码长度必须在6到20个字符之间', 
      trigger: 'blur' 
    }
  ]
}

onMounted(() => {
  // 如果是从注册页面跳转来的，自动填充表单
  const { idNumber, password } = router.currentRoute.value.query
  if (idNumber && password) {
    loginForm.value.idNumber = idNumber
    loginForm.value.password = password
    
    // 清除 URL 中的敏感信息
    router.replace({
      path: '/login',
      query: {}
    })
  }
})

const handleLogin = async () => {
  if (!loginFormRef.value) return
  try {
    loading.value = true
    //验证表单
    await loginFormRef.value.validate()

     // 调用登录接口
     const res = await login(loginForm.value)
     // 登录成功
    if (res.code === 200) {
      const userInfo = {
        user: {name: res.data.realname,},
        token: res.data.token,
        // role: '', // 这里可以根据实际情况设置角色
        // permissions: []
      }
      if(res.data.role === 'admin'){
        userInfo.role = 'admin'
        // router.push(`/admin`) // 或根据实际角色跳转
      } else if(res.data.role === 'teacher'){
        userInfo.role = 'teacher'
        // router.push(`/teacher`) // 或根据实际角色跳转
      } else if(res.data.role === 'student'){
        userInfo.role = 'student'
        // router.push(`/student`) // 或根据实际角色跳转
      }
      

      // 设置用户信息
      authStore.setUserInfo(userInfo)
      ElMessage.success('登录成功')

 // 获取完整用户信息
      try {
        await authStore.loadUserInfo()
      } catch (error) {
        console.error('加载用户信息失败:', error)
        // 即使加载用户信息失败，也继续进行路由跳转
      }

      // 路由跳转
      router.push(`/${userInfo.role}`)
    } else {
      ElMessage.error(res.message || '登录失败')
    }
  } catch (error) {
    console.error('登录错误:', error)
    ElMessage.error(error.message || '登录失败，请稍后重试')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.login-card h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.register-link {
  margin-left: 10px;
}

/* 测试提示面板的样式 */
/* .test-accounts {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.test-accounts p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.test-accounts ul {
  margin: 10px 0 0 0;
  padding-left: 20px;
  color: #606266;
  font-size: 13px;
}

.test-accounts li {
  margin: 5px 0;
} */
</style> 